<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="标题" prop="bannerTitle">
        <el-input
          v-model="queryParams.bannerTitle"
          placeholder="请输入轮播图标题"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="位置" prop="position">
        <el-input v-model="queryParams.position" placeholder="位置" clearable style="width: 120px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="carouselList"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      :default-sort="defaultSort"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="ID"
        align="center"
        prop="bannerId"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
      />
      <el-table-column
        label="标题"
        align="center"
        prop="bannerTitle"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="图片" align="center" prop="bannerImage">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 60px"
            :src="scope.row.bannerImage"
            :preview-src-list="[scope.row.bannerImage]"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="链接"
        align="center"
        prop="bannerUrl"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="目标类型"
        align="center"
        prop="targetType"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
      />
      <el-table-column label="目标ID" align="center" prop="targetId" />
      <el-table-column
        label="位置"
        align="center"
        prop="position"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
      />
      <el-table-column
        label="排序"
        align="center"
        prop="sortOrder"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
      />
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        width="180"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改轮播图对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="carouselRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="bannerTitle">
          <el-input v-model="form.bannerTitle" placeholder="请输入轮播图标题" />
        </el-form-item>
        <el-form-item label="图片" prop="bannerImage">
          <el-input v-model="form.bannerImage" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="链接" prop="bannerUrl">
          <el-input v-model="form.bannerUrl" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="目标类型" prop="targetType">
          <el-input v-model="form.targetType" placeholder="目标类型" />
        </el-form-item>
        <el-form-item label="目标ID" prop="targetId">
          <el-input v-model="form.targetId" placeholder="目标ID" />
        </el-form-item>
        <el-form-item label="位置" prop="position">
          <el-input v-model="form.position" placeholder="位置" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择开始时间" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Carousel">
import { listCarousel, getCarousel, delCarousel, addCarousel, updateCarousel } from "@/api/homepage/carousel";

const { proxy } = getCurrentInstance();

const carouselList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 默认排序
const defaultSort = ref({ prop: 'sortOrder', order: 'ascending' });

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    bannerTitle: undefined,
    position: undefined,
    orderByColumn: 'sort_order',
    isAsc: 'asc'
  },
  rules: {
    bannerTitle: [
      { required: true, message: "轮播图标题不能为空", trigger: "blur" }
    ],
    bannerImage: [
      { required: true, message: "轮播图图片不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

function getList() {
  loading.value = true;
  listCarousel(queryParams.value).then(response => {
    carouselList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function cancel() {
  open.value = false;
  reset();
}

function reset() {
  form.value = {
    bannerId: undefined,
    bannerTitle: undefined,
    bannerImage: undefined,
    bannerUrl: undefined,
    targetType: undefined,
    targetId: undefined,
    position: undefined,
    sortOrder: 0,
    startTime: undefined
  };
  proxy.resetForm("carouselRef");
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.bannerId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 排序触发事件 */
function handleSortChange(column) {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order === 'ascending' ? 'asc' : 'desc';
  getList();
}

function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加轮播图";
}

function handleUpdate(row) {
  reset();
  const bannerId = row.bannerId || ids.value[0];
  getCarousel(bannerId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改轮播图";
  });
}

function submitForm() {
  proxy.$refs["carouselRef"].validate(valid => {
    if (valid) {
      if (form.value.bannerId != null) {
        updateCarousel(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCarousel(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleDelete(row) {
  const bannerId = row.bannerId || ids.value[0];
  proxy.$modal.confirm('是否确认删除轮播图编号为"' + bannerId + '"的数据项？').then(function() {
    return delCarousel(bannerId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

getList();
</script> 